<template>
	<view>
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">导出 Excel</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace" :orderby="orderby"
				:getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual"
				@load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'"   stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">店铺logo</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'title')" sortable
							@sort-change="sortChange($event, 'title')">店铺名称</uni-th>
						<uni-th align="center" filter-type="select" :filter-data="filterTypeshopData"
							@filter-change="filterTypeshop">
							店铺分类
						</uni-th>
						<uni-th align="center">
							配送时效
						</uni-th>
						<uni-th align="center">店铺评分</uni-th>
						<!-- <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'monthly_sales')" sortable @sort-change="sortChange($event, 'monthly_sales')">月销售量</uni-th> -->
						<uni-th align="center">总销售量</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'tel')">手机号码</uni-th>
						<uni-th align="center">创建人</uni-th>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'goods')" sortable
							@sort-change="sortChange($event, 'goods')">商品量</uni-th>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'page_view')" sortable
							@sort-change="sortChange($event, 'page_view')">浏览量</uni-th>
						<uni-th align="center" v-if="prommissionRate" >
							店铺佣金比
						</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'disabled_status')">店铺状态</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'business_status')">经营状态</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">
							<image :src="item.logo.url" style="width:35px;height:35px; border-radius:50%;"></image>
						</uni-td>

						<uni-td align="center">
							<text class="titleApp">
								{{item.title}}
							</text>
						</uni-td>
						<uni-td align="center">{{item.categories && item.categories[0] && item.categories[0].text}}</uni-td>
						<uni-td align="center">{{item.delivery_timeliness}}</uni-td>
						<uni-td align="center">{{item.score}}</uni-td>
						<!-- <uni-td align="center">{{item.monthly_sales}}</uni-td> -->
						<uni-td align="center">{{item.total_sales}}</uni-td>
						<uni-td align="center">
							<text class="TelApp">
								
							{{ initPhone(item.tel||'')}}
							</text>
							
						</uni-td>
						<uni-td align="center"
							v-if="item.create_uid && item.create_uid[0]">{{item.create_uid[0].nickname}}</uni-td>
						<uni-td align="center" v-else>--</uni-td>
						<uni-td align="center">{{item.goods}}</uni-td>
						<uni-td align="center">{{item.page_view}}</uni-td>
						<uni-td align="center" v-if="prommissionRate" >
							{{item.commission_rate?item.commission_rate/10+'%':'暂未设置'}}
						</uni-td>
						<uni-td align="center">
							{{item.disabled_status == true ? '✔️' : '✖️'}}
						</uni-td>
						<uni-td align="center">
							<text v-if="item.pause_duration > Date.now()"  >
								<uni-dateformat
									:date="item.pause_duration" format="MM月dd日hh:ss"
								></uni-dateformat>
								<text> 后营业</text>
							</text>
							<text v-else >
								{{item.business_status == true ? '✔️' : '✖️'}}
							</text>
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button
									@click="navigateTo('/pages/shop/goods/list?store_id='+item._id+'&store='+item.title, false)"
									class="uni-button" size="mini" type="primary">商品管理</button>
								<button
									@click="navigateTo('/pages/shop/shop-categories/list?store_id='+item._id+'&store='+item.title, false)"
									class="uni-button" size="mini" type="primary">分类管理</button>
								<button v-if="prommissionRate" @click="setCommission(item)" class="uni-button" size="mini"
									type="primary">佣金设置</button>
								<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
									type="primary">修改</button>
								<button @click="confirmDelete(item)" class="uni-button" size="mini" type="warn">删除</button>
								<button size="mini" @click="goUrl('/pages/notice/shop/add?_uid='+item._id)" style="margin:0 5px" >
									发送通知
								</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<!-- 当前店铺佣金 -->
		<uni-popup ref="showStatus" type="center" style="border-radius:20px;" backgroundColor="#fff">
			<view class="popup">
				<view class="title">
					{{commission_rate.title}}
				</view>
				<view class="body">
					<view style="margin:20rpx 0">
						当前店铺佣金: <text style="color:#ff6600">
							{{commission_rate.commission_rate?(commission_rate.commission_rate / 10)+'%':'暂未设置'}}
						</text>
					</view>
					
					<view  style="margin:20rpx 0" >
						<view>
							店铺佣金比例是指商家在交易中需要支付给平台维护的费用比例。
						</view>
						<view style="margin:10px ; color:red;font-size:13px">
							<view>
								"在修改之前必须经过上级领导层允许或跟商家100%确定协商后修改。"
							</view>
							<view>店铺佣金设置，请不要私自修改。</view>
							<view>否则后果自负！</view>
						</view>
					</view>
					<view style="margin:50px 0;display:flex">
						<text>
							佣金抽成
							<text style="color:red" >
								千分之
							</text>
						</text>
						<view style="margin:0 10px" >
							<uni-number-box :min="0" :step="10" v-model="commission_rate.commission_rate" :max="300"></uni-number-box>
						</view>
						<text>
							
						</text>
					</view>
					<button @click="setRate" class="uni-button" size="mini" type="primary"  >
						保存设置
					</button>
					<button @click="this.$refs.showStatus.close()" class="uni-button" size="mini" type="primary"  >
						取消
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../../js_sdk/validator/shop.js';
import Util from "@/js_sdk/validator/util.js"
	import { areaPower ,getArea } from "@/js_sdk/manage-area/manage.js";
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '_id desc' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1
	const orderByMapping = {"ascending": "asc","descending": "desc"}
	function numberRange(start, end) {
		return Array.from(new Array(end + 1).keys()).slice(start);
	}
	export default {
		data() {
			return {
				// 是否拥有设置佣金权限
				prommissionRate:false,
				// 佣金数据
				commission_rate:{
				},
				filterTypeshopData: [
				],
				collectionList: [db.collection('shop').field(
						'title,categories,pause_duration,commission_rate,area_all,delivery_timeliness,score,monthly_sales,total_sales,region,address,start_business_hours1,end_business_hours1,start_business_hours2,end_business_hours2,logo,photo,tel,intro,create_uid,goods,page_view,evaluate,disabled_status,business_status'
					).getTemp(), db.collection('opendb-mall-categories').field('_id, name as text').getTemp(), db
					.collection('opendb-city-china').field('code,name as text,eq(type,2) as isleaf').getTemp(), db
					.collection('uni-id-users').where("userid == create_uid").field('_id as userid,nickname').getTemp()
				],
				query: '',
				where:{
					"area_all.value":db.command.in( areaPower() ),
				},
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"score_data": numberRange(0, 5),
						"score_index": null
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "shop.xls",
					"type": "xls",
					"fields": {
						"店铺名称": "title",
						"店铺分类": "categories",
						"配送时效": "delivery_timeliness",
						"店铺评分": "score",
						"月销售量": "monthly_sales",
						"总销售量": "total_sales",
						"店铺地址": "region",
						"详细地址": "address",
						"开始营业时间段1": "start_business_hours1",
						"结束营业时间段1": "end_business_hours1",
						"开始营业时间段2": "start_business_hours2",
						"结束营业时间段2": "end_business_hours2",
						"店铺logo": "logo",
						"店铺照片": "photo",
						"手机号码": "tel",
						"简介": "intro",
						"创建人": "create_uid",
						"浏览量": "page_view",
						"评价量": "evaluate",
						"店铺状态": "disabled_status",
						"暂停时间": "pause_duration",
						"创建时间": "create_time",
					}
				},
				exportExcelData: []
			}
		},
		onLoad(e) {
			if (e._uid) {
				this.where = {
					_id: e._uid
				}
			}
			this.prommissionRate = this.isAdmin(['admin','region'])
			this._filter = {}
			this.getCategories()
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			goUrl(Url){
				uni.navigateTo({
					url:Url
				})
			},
			onqueryload(data) {
				this.exportExcelData = data
			},
			getCategories() {
				db.collection("opendb-mall-categories").where(`name != '全部'`).field("name as text,_id as value,sort").get({
					getOne: false
				}).then(res => {
					this.filterTypeshopData = res.result.data
				})
			},
			filterTypeshop(val) {
				if (val.filter.length) {
					this.where = {
						categories: db.command.elemMatch({
							_id: db.command.in(val.filter)
						}),
						"area_all.value":db.command.in( areaPower() ),
					}
				} else {
					this.where = this.where
				}

				this.$nextTick(() => {
					this.loadData()
				})
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = {
					"area_all.value":db.command.in( areaPower() ),
					...this.getWhere()
				}
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			isAdmin(admin=[]){
				return Util.userHasPermission(admin)
			},
			initPhone(mobile){
				return Util.formatPhoneNumber(mobile)
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			setCommission(item){
				this.$refs.showStatus.open()
				this.commission_rate = item
				
				// item.commission_rate? this.commission_rate.commission_rate=item.commission_rate/10 : 0
			},
			// 保存设置当前店铺抽成
			// 保存设置当前店铺抽成
			setRate(){
				db.collection("shop").doc(this.commission_rate._id).update({
					commission_rate:parseFloat(this.commission_rate.commission_rate)
				}).then(res=>{
					this.commission_rate.commission_rate = parseFloat(this.commission_rate.commission_rate)
					uni.showModal({
						title:"佣金设置成功",
						content:`${this.commission_rate.title}店已经成功将佣金设置为：${parseFloat(this.commission_rate.commission_rate / 10)}%`
					})
					this.$refs.showStatus.close()
				}).catch(error=>{
					if(parseFloat(this.commission_rate.commission_rate) < 10){
						uni.showModal({
							title:"设置失败",
							content:"佣金最少不能不能小于千分之10"
						})
					}else if(parseFloat(this.commission_rate.commission_rate) > 400){
						uni.showModal({
							title:"设置失败",
							content:"佣金最少不能不能大于千分之400"
						})
					}else{
						uni.showModal({
							title:"环境异常，请重试",
						})
					}
					
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(item) {
				const db = uniCloud.database();
				db.collection('shop-categories').where({
					shop_id: item._id
				}).get({
					getOne: true
				}).then(res => {
					if (item.goods == 0 && !res.result.data) {
						//将店铺审核表和店铺申请表删除
						db.collection('shop_examine').where({
							create_uid: item.create_uid
						}).remove();
						db.collection('shop_authentication').where({
							user_id: item.create_uid
						}).remove();
						this.$refs.udb.remove(item._id, {
							success: (res) => {
								this.$refs.table.clearSelection()
							}
						})
					} else {
						uni.showModal({
							content: '该店铺下有分类或商品，禁止删除！',
							showCancel: false
						})
					}
				});
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = '_id desc'
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = {
					"area_all.value":db.command.in( areaPower() ),
					...filterToWhere(this._filter, db.command)
				}
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			}
		}
	}
</script>

<style lang="scss" >
	.popup{
		border-radius:10rpx;
		width:500px;
		min-height:200px;
		padding:30rpx;
		.uni-button{
			margin:0 50rpx;
		}
		
	}
</style>